package com.zabra.zl.ui.sale;

import android.app.Dialog;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.zabra.zl.Config;
import com.zabra.zl.R;
import com.zabra.zl.base.BaseMvpActivity;
import com.zabra.zl.data.DetailsDealBean;
import com.zabra.zl.data.SimpleBean;
import com.zabra.zl.data.StockBean;
import com.zabra.zl.ui.buy.presenter.BuyPresenter;
import com.zabra.zl.ui.sale.contract.SaleContract;
import com.zabra.zl.ui.sale.presenter.SalePresenter;
import com.zabra.zl.utils.DialogUtils;
import com.zabra.zl.utils.MaptoJsonUtils;
import com.zabra.zl.utils.ShowDialogUtils;
import com.zabra.zl.utils.ToastUtil;

import java.text.DecimalFormat;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class SaleActivity extends BaseMvpActivity<SalePresenter> implements SaleContract.View {


    @BindView(R.id.back)
    LinearLayout back;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.et_search)
    TextView etSearch;
    @BindView(R.id.tv_stock)
    TextView tvStock;
    @BindView(R.id.tv_jian1)
    TextView tvJian1;
    @BindView(R.id.tv_text1)
    TextView tvText1;
    @BindView(R.id.tv_jia1)
    TextView tvJia1;
    @BindView(R.id.tv_harden)
    TextView tvHarden;
    @BindView(R.id.tv_limit)
    TextView tvLimit;
    @BindView(R.id.tv_jian2)
    TextView tvJian2;
    @BindView(R.id.tv_text2)
    TextView tvText2;
    @BindView(R.id.tv_jia2)
    TextView tvJia2;
    @BindView(R.id.tv_buy)
    TextView tvBuy;
    @BindView(R.id.tv_price)
    TextView tvPrice;
    @BindView(R.id.sale_price5)
    TextView salePrice5;
    @BindView(R.id.sale_num5)
    TextView saleNum5;
    @BindView(R.id.sale_price4)
    TextView salePrice4;
    @BindView(R.id.sale_num4)
    TextView saleNum4;
    @BindView(R.id.sale_price3)
    TextView salePrice3;
    @BindView(R.id.sale_num3)
    TextView saleNum3;
    @BindView(R.id.sale_price2)
    TextView salePrice2;
    @BindView(R.id.sale_num2)
    TextView saleNum2;
    @BindView(R.id.sale_price1)
    TextView salePrice1;
    @BindView(R.id.sale_num1)
    TextView saleNum1;
    @BindView(R.id.buy_price5)
    TextView buyPrice5;
    @BindView(R.id.buy_num5)
    TextView buyNum5;
    @BindView(R.id.buy_price4)
    TextView buyPrice4;
    @BindView(R.id.buy_num4)
    TextView buyNum4;
    @BindView(R.id.buy_price3)
    TextView buyPrice3;
    @BindView(R.id.buy_num3)
    TextView buyNum3;
    @BindView(R.id.buy_price2)
    TextView buyPrice2;
    @BindView(R.id.buy_num2)
    TextView buyNum2;
    @BindView(R.id.buy_price1)
    TextView buyPrice1;
    @BindView(R.id.buy_num1)
    TextView buyNum1;
    @BindView(R.id.ll_title)
    LinearLayout llTitle;
    @BindView(R.id.recycler)
    RecyclerView recycler;
    @BindView(R.id.rl_nodata)
    RelativeLayout rlNodata;
    @BindView(R.id.bt_sale)
    TextView btSale;

    private Adp adp;
    private int orderId;
    private String strCode, strName, strNum, strPrice, strMax, strBpFundsRId;
    private Dialog dialog;
    private DecimalFormat decimalFormat = new DecimalFormat("0.00");
    private Disposable disposable;

    @Override
    public int getLayoutId() {
        return R.layout.activity_sale;
    }

    @Override
    public void initView() {
        tvTitle.setText("卖出");
        orderId = getIntent().getExtras().getInt("orderid");
        mPresenter = new SalePresenter();
        mPresenter.attachView(this);
        keyList.add("bpOrderId");
        valueList.add(orderId + "");
        mPresenter.getData(MaptoJsonUtils.Simple(keyList, valueList));

    }

    @Override
    public void showLoading() {
        dialog = DialogUtils.showDialog_progressbar(this);
    }

    @Override
    public void hideLoading() {
        DialogUtils.closeDialog(dialog);
    }

    @Override
    public void onError(Throwable throwable) {
        DialogUtils.closeDialog(dialog);
    }

    @Override
    public void onSuccess(StockBean bean) {
        if (bean.getRespCode().equals(Config.SUCCESS)) {
            StockBean.RespDataBean respData = bean.getRespData();
            tvStock.setText(respData.getSharesName());
            etSearch.setText(strCode);
            //涨停
            tvHarden.setText(respData.getNowDayTop());
            //跌停
            tvLimit.setText(respData.getNowDayLoss());
            //当前价
            tvText1.setText(respData.getNowPrice());
            //可卖
            strMax = respData.getNowNum() + "";
            tvBuy.setText(strMax);
            refreshData(respData);
            /**
             * rxjava 定时任务，每5秒执行一次
             * */
            disposable = Observable.interval(0, 5, TimeUnit.SECONDS)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Consumer<Long>() {
                        @Override
                        public void accept(Long aLong) throws Exception {
                            mPresenter.getDataFresh(strCode, orderId);
                        }
                    });

        } else if (bean.getRespCode().equals(Config.TOKENOUT)) {
            ShowDialogUtils.restLoginDialog(this);
        } else {
            ToastUtil.showToast(this, bean.getRespDesc());
        }
    }

    @Override
    public void onSuccessFresh(StockBean bean) {
        if (bean.getRespCode().equals(Config.SUCCESS)) {
            refreshData(bean.getRespData());
        } else if (bean.getRespCode().equals(Config.TOKENOUT)) {
            ShowDialogUtils.restLoginDialog(this);
        } else {
            ToastUtil.showToast(this, bean.getRespDesc());
        }
    }

    @Override
    public void onSuccess(DetailsDealBean bean) {
        if (bean.getRespCode().equals(Config.SUCCESS)) {
            //持仓数组
            List<DetailsDealBean.PositionsBean> list = bean.getPositions();
            if (list.size() == 0) {
                llTitle.setVisibility(View.GONE);
                rlNodata.setVisibility(View.VISIBLE);
            } else {
                llTitle.setVisibility(View.VISIBLE);
                rlNodata.setVisibility(View.GONE);
                recycler.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
                recycler.setNestedScrollingEnabled(false);
                adp = new Adp(R.layout.item_haved, list);
                recycler.setAdapter(adp);
                adp.openLoadAnimation();
                adp.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                        strBpFundsRId = list.get(position).getBpFundsRId() + "";
                        strCode = list.get(position).getSharesCode();
                        mPresenter.getData(strCode, orderId);
                    }
                });
            }
        } else if (bean.getRespCode().equals(Config.TOKENOUT)) {
            ShowDialogUtils.restLoginDialog(this);
        } else {
            ToastUtil.showToast(this, bean.getRespDesc());
        }
    }

    @Override
    public void onSuccess(SimpleBean bean) {
        if (bean.getRespCode().equals(Config.SUCCESS)) {
            showBottomDialog();
        } else if (bean.getRespCode().equals(Config.TOKENOUT)) {
            ShowDialogUtils.restLoginDialog(this);
        } else if (bean.getRespCode().equals(Config.SEND)) {
            showBottomDialog();
        } else {
            ToastUtil.showToast(this, bean.getRespDesc());
        }
    }


    private void showBottomDialog() {
        final Dialog dialog = new Dialog(this, R.style.DialogTheme);
        View view = View.inflate(this, R.layout.dialog_submit, null);
        dialog.setContentView(view);
        Window window = dialog.getWindow();
        window.setGravity(Gravity.BOTTOM);
        window.setWindowAnimations(R.style.main_menu_animStyle);
        window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        dialog.show();
        TextView tvName = view.findViewById(R.id.dialog_name);
        TextView tvNum = view.findViewById(R.id.dialog_num);
        TextView tvPrice = view.findViewById(R.id.dialog_price);
        tvName.setText(strName);
        tvNum.setText(strNum);
        tvPrice.setText(strPrice);
        view.findViewById(R.id.tv_query).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ToastUtil.showToast(view.getContext(), "委托查询");
                dialog.dismiss();
            }
        });
        view.findViewById(R.id.tv_ok).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
                dialog.dismiss();
            }
        });
    }


    @OnClick({R.id.back, R.id.tv_jian1, R.id.tv_jia1, R.id.tv_jian2, R.id.tv_jia2, R.id.bt_sale})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.tv_jian1:
                jianDouble(tvText1);
                count();
                break;
            case R.id.tv_jia1:
                jiaDouble(tvText1);
                count();
                break;
            case R.id.tv_jian2:
                jianInt(tvText2);
                count();
                break;
            case R.id.tv_jia2:
                jiaInt(tvText2);
                count();
                break;
            case R.id.bt_sale:
                strCode = etSearch.getText().toString().trim();
                strName = tvStock.getText().toString().trim();
                strPrice = tvText1.getText().toString().trim();
                strNum = tvText2.getText().toString().trim();
                mPresenter.getData(strCode, strName, strPrice, strNum, "", orderId + "", strBpFundsRId);
                break;
        }
    }

    private void jianDouble(TextView textView) {
        String s = textView.getText().toString();
        double sDouble = Double.parseDouble(s);
        if (sDouble <= 0) {
            return;
        } else {
            decimalFormat = new DecimalFormat("0.00");
            sDouble = sDouble - 0.01;
            textView.setText(decimalFormat.format(sDouble));
        }
    }

    private void jiaDouble(TextView textView) {
        String s = textView.getText().toString();
        double sDouble = Double.parseDouble(s);
        decimalFormat = new DecimalFormat("0.00");
        sDouble = sDouble + 0.01;
        textView.setText(decimalFormat.format(sDouble));
    }

    private void jianInt(TextView textView) {
        String s = textView.getText().toString();
        int sDouble = Integer.parseInt(s);
        if (sDouble <= 0) {
            return;
        } else {
            sDouble = sDouble - 100;
            textView.setText(sDouble + "");
        }
    }

    private void jiaInt(TextView textView) {
        String s = textView.getText().toString();
        int sDouble = Integer.parseInt(s);
        int max = Integer.parseInt(strMax);
        if (sDouble >= max) {
            return;
        } else {
            int i = max - sDouble;
            if ((i % 100) == 0) {
                sDouble = sDouble + 100;
            } else {
                sDouble = sDouble + ((i % 100));
            }
        }

        textView.setText(sDouble + "");
    }

    private void count() {
        String price = tvText1.getText().toString().trim();
        String num = tvText2.getText().toString().trim();
        double d = Double.parseDouble(price);
        int i = Integer.parseInt(num);
        tvPrice.setText(decimalFormat.format(d * i));
    }

    private void refreshData(StockBean.RespDataBean respData) {
        salePrice5.setText(respData.getSharesInfos().get(0).getPrice());
        salePrice4.setText(respData.getSharesInfos().get(1).getPrice());
        salePrice3.setText(respData.getSharesInfos().get(2).getPrice());
        salePrice2.setText(respData.getSharesInfos().get(3).getPrice());
        salePrice1.setText(respData.getSharesInfos().get(4).getPrice());
        saleNum5.setText(respData.getSharesInfos().get(0).getNumber());
        saleNum4.setText(respData.getSharesInfos().get(1).getNumber());
        saleNum3.setText(respData.getSharesInfos().get(2).getNumber());
        saleNum2.setText(respData.getSharesInfos().get(3).getNumber());
        saleNum1.setText(respData.getSharesInfos().get(4).getNumber());

        buyPrice5.setText(respData.getSharesInfos().get(5).getPrice());
        buyPrice4.setText(respData.getSharesInfos().get(6).getPrice());
        buyPrice3.setText(respData.getSharesInfos().get(7).getPrice());
        buyPrice2.setText(respData.getSharesInfos().get(8).getPrice());
        buyPrice1.setText(respData.getSharesInfos().get(9).getPrice());

        buyNum5.setText(respData.getSharesInfos().get(5).getNumber());
        buyNum4.setText(respData.getSharesInfos().get(6).getNumber());
        buyNum3.setText(respData.getSharesInfos().get(7).getNumber());
        buyNum2.setText(respData.getSharesInfos().get(8).getNumber());
        buyNum1.setText(respData.getSharesInfos().get(9).getNumber());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (disposable!=null){
            disposable.dispose();
        }
    }
}
